import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Alert, Input } from 'antd';
import { randomKey } from '../../../../utils/utils';
import CodeReturnItem from './codeReturnItem';

/**
 * @component CodeReturn 命中代码返回配置组件
 * @prop {Array} value 组件值
 * @prop {Function} onChange 改变值之后的回调
 * @prop {Object} variable 可被用于选择的变量对象
 * @prop {Boolean} disabled 是否只读,默认false
 * {
    "scope": "anyApp|anyEvent|ownerEvent|ownerStrategy",
    "code": "",
    "msg": "",
    "enabled": true
  }
 */

export default function CodeReturn(props) {
  const [codes, setCodes] = useState([]);
  const [keyword, setKeyword] = useState('');

  useEffect(() => {
    if (props.value && props.value.length > 0) {
      setCodes(initData(props.value));
    } else {
      setCodes([]);
    }
  }, [props.value]);

  function initData(data) {
    const newData = data.map(item => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  //添加规则
  function addAction() {
    const code = {
      prior: codes.length + 1,
      enabled: true,
      id: randomKey()
    };
    codes.push(code);
    setCodes(Object.assign([], codes));
    props.onChange && props.onChange(codes);
  }

  // 修改item的value回调
  function handleChange(id, value) {
    for (let i = 0; i < codes.length; i++) {
      if (codes[i].id === id) {
        codes[i] = value;
      }
    }
    setCodes(Object.assign([], codes));
    props.onChange && props.onChange(codes);
  }

  // 删除
  function del(index) {
    codes.splice(index, 1);
    setCodes(Object.assign([], codes));
    props.onChange && props.onChange(codes);
  }

  // 移动
  function move(item, index, step) {
    // 下移
    if (step === 'down') {
      codes.splice(index, 1); //移除当前项
      codes.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      codes.splice(index, 1); //移除当前项
      codes.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    setCodes(Object.assign([], codes));
    props.onChange && props.onChange(codes);
  }

  // 搜索
  function handleSearch(e) {
    setKeyword(e.target.value);
  }

  const filterCodes = keyword ? codes.filter(item => item.code && item.code.indexOf(keyword) !== -1) : codes;
  return (
    <div style={{ marginTop: '20px' }} className='rule-wp'>
      <Alert
        message={
          '注：返回代码新建后不可修改，如执行删除操作，请先确保线上业务已不再使用此返回代码，否则可能影响您的线上业务。'
        }
        type='info'
        style={{ marginBottom: '20px' }}
      />
      <Row type='flex' justify='space-between' gutter={10} style={{ marginBottom: '10px' }}>
        <Col>
          {!props.disabled && (
            <Button
              type='primary'
              onClick={() => {
                addAction();
              }}
              disabled={Object.keys(props.variable).length === 0}
            >
              添加返回代码
            </Button>
          )}
        </Col>
        <Col>
          <Input.Search
            className='search-clear'
            placeholder='请输入返回代码进行搜索'
            onChange={handleSearch}
            disabled={codes.length === 0}
            onPressEnter={e => e.preventDefault()}
          />
        </Col>
      </Row>
      <Row type='flex' justify='space-between' align='middle' gutter={20} className='rule-hd'>
        <Col span={2}>序号</Col>
        <Col span={5}>作用范围</Col>
        <Col span={5}>返回代码</Col>
        <Col span={6}>返回信息</Col>
        <Col span={3}>启用</Col>
        {!props.disabled && <Col span={3}>操作</Col>}
      </Row>
      {filterCodes.map((item, index) => {
        return (
          <CodeReturnItem
            {...props}
            value={item}
            index={index + 1}
            key={item.id}
            variable={props.variable}
            disabled={props.disabled}
            onChange={handleChange.bind(this, item.id)}
            onDel={del.bind(this, index)}
            onMove={move.bind(this, item, index)}
            len={codes.length}
            codes={props.codes}
            compareData={(props.compareData && props.compareData[index]) || undefined}
          />
        );
      })}
    </div>
  );
}
